package com.sftz.modules.admin.authority.role.service.impl;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;

import com.sftz.framework.res.entities.SFunctionEntity;
import com.sftz.framework.res.entities.SRoleEntity;
import com.sftz.framework.res.entities.SRoleFunctionMapEntity;
import com.sftz.modules.admin.authority.role.form.RoleModForm;
import com.sftz.modules.admin.authority.role.service.RoleService;
import com.uxuexi.core.common.util.Util;
import com.uxuexi.core.db.dao.IDbDao;
import com.uxuexi.core.web.util.FormUtil;

@IocBean(name = "roleService")
public class RoleServiceImpl implements RoleService {

	@Inject
	private IDbDao dbDao;

	@Override
	public boolean update(RoleModForm form) {
		//修改角色实体
		FormUtil.modify(dbDao, form, SRoleEntity.class);
		updateSRoleFunctionMapEntity(form);
		return true;
	}

	/**修改角色功能关系*/
	public void updateSRoleFunctionMapEntity(RoleModForm form) {

		String functionIds = form.getFunctionIds();
		//根据角色查询关系
		Integer roleId = Integer.parseInt(form.getId() + "");
		List<SRoleFunctionMapEntity> before = dbDao.query(SRoleFunctionMapEntity.class,
				Cnd.where("roleId", "=", roleId), null);
		//欲更新为
		List<SRoleFunctionMapEntity> after = new ArrayList<SRoleFunctionMapEntity>();

		if (!Util.isEmpty(functionIds)) {
			String[] funIds = functionIds.split(",");
			for (String funId : funIds) {
				SRoleFunctionMapEntity each = new SRoleFunctionMapEntity();
				each.setRoleId(roleId);
				each.setFunctionId(Integer.valueOf(funId));

				after.add(each);
			}
		}
		dbDao.updateRelations(before, after);
	}

	@Override
	public Map<String, Object> findRole(long id) {
		Map<String, Object> obj = new HashMap<String, Object>();

		//全部功能
		List<SFunctionEntity> allFunc = dbDao.query(SFunctionEntity.class, null, null);

		//根据角色查询关系
		List<SRoleFunctionMapEntity> relation = dbDao.query(SRoleFunctionMapEntity.class, Cnd.where("roleId", "=", id),
				null);
		//如果角色有功能
		if (!Util.isEmpty(relation)) {
			//该角色的功能id集合
			List<Integer> existsFuncIds = new ArrayList<Integer>();
			for (SRoleFunctionMapEntity r : relation) {
				existsFuncIds.add(r.getFunctionId());
			}

			for (SFunctionEntity f : allFunc) {
				if (existsFuncIds.contains(f.getId())) {
					f.setChecked("true");
				}
			}
		}
		obj.put("list", allFunc);
		obj.put("role", dbDao.fetch(SRoleEntity.class, id));
		return obj;
	}

}
